import Vue from 'vue'

// 1.引入异步请求框架
import axios from 'axios'
import VueAxios from 'vue-axios'
// 2.引入定义的接口列表
import apiList from '@/apis'
import JSONBIG from 'json-bigint'
// 3.引入根路径配置
// 引入存储
import store from '@/store'
import router from '../router'

Vue.use(VueAxios, axios)

// 4.设置接口超时时间
axios.defaults.timeout = 60000000
axios.defaults.withCredentials = true

// 处理id值过大问题
axios.defaults.transformResponse = [
  function (data) {
    const json = JSONBIG({
      storeAsString: true
    })
    const res = json.parse(data)
    return res
  }
]

// 需要引出去的变量
var api = {}

/**
 * 请求方法:默认post
 * 系统请求上下文:默认jd
 * contentType：默认json
 *
 * [注册接口]
 * @param  {String} name   [接口别名]
 * @param  {String} url    [接口URL]
 * @param  {String} method [请求方式]
 *
 */
function putApi(name, url, method, serviceName, contentType) {
  if (!method) {
    method = 'post'
  }

  if (!serviceName) {
    serviceName = 'admin'
  }

  // json结构转表单结构
  let config = {}
  if (contentType === 'form') {
    config = {
      transformRequest: [function (data) {
        let ret = ''
        for (let p in data) {
          ret += encodeURIComponent(p) + '=' + encodeURIComponent(data[p]) + '&'
        }
        return ret
      }],
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      }
    }
  }

  /**
   * [往api对象集合添加接口]
   * @param  {Object}   context  [上下文环境，即this对象]
   * @param  {Object}   options  [请求参数]
   *
   */
  api[name] = (options) => {
    /** 默认添加显示load加载 */
    options = Object.assign({needLoad: true}, options || {})
    let needLoad = options.needLoad
    delete options.needLoad
    if (needLoad) {
      Vue.prototype.$bus.emit('showLoad')
    }

    // 开发环境&与打包环境base值计算
    var base = ''
    // if (process.env.NODE_ENV === 'development') {
    //     if(serviceName == 'admin'){
    //         base = '/proxyAdmin'
    //     }else if(serviceName == 'es'){
    //         base = '/proxyEs'
    //     }
    // }else{
    //     if(serviceName== 'admin'){
    //         base = rootUrl.adminUrl;
    //     }else if(serviceName == 'es'){
    //         base = rootUrl.esUrl;
    //     }
    // }
    return Vue.axios[method](base + url, method === 'post' ? options : {params: options}, config)
      .then((back) => {
        if (needLoad) {
          Vue.prototype.$bus.emit('hideLoad')
        }
        // alert(back.data.code);
        if (back) {
          if (back.data.code === '00000' || back.data.code === 200 || back.data.status === 1) {
            return back.data
          } else if (back.data.code === '10001') {
            /* Vue.prototype.$message({
               type: 'error',
               message: back.data.data
             }); */
            // window.location.href = back.data.data;
          } else if (back.data.code === '10904') {
            //   Vue.prototype.$message({
            //    type: 'error',
            //    offset:240,
            //    message: '登录超时，请重新登录'
            //  });
            // setTimeout(function(){
            //   window.location.href = back.data.data;
            // },1500)
          } else {
            return back.data
          }
        } else {
          // eslint-disable-next-line prefer-promise-reject-errors
          return Promise.reject('未知错误')
        }
      }).catch((err) => {
        console.log(err)
        if (needLoad) {
          Vue.prototype.$bus.emit('hideLoad')
        }
        if (err.code === '10904') {
          // Vue.prototype.$Message.error('请重新登录')
          setTimeout(function () {
            window.location.href = err.data
          }, 1000)
        }
        /*           Vue.prototype.$Message.destroy();
                  Vue.prototype.$Message.error({
                      content: err.message || '请重新登录',
                      duration: 3
                  }); */
        /** 登录态过期 */
        /*           if (err.code === 401 || !err.message) {
                      setTimeout(function() {
                          router.replace({
                              name: 'Login'
                          })
                      }, 2000);
                  } */
        return Promise.reject(err)
      })
  }
}

console.log('正在初始化http接口')
/* 执行接口的注册 */
for (let i in apiList) {
  putApi(i, apiList[i].url, apiList[i].method, apiList[i].serviceName, apiList[i].contentType)
}
console.log('http接口列表详情:', api)

export default api

// 请求拦截---添加token
axios.interceptors.request.use(function (config) {
  let token = store.getToken()
  console.log('请求拦截:', config.url, 'token=' + token)
  if (config.url.includes('/user/login')) {
    // 不需要token
  } else {
    if (!token) {
      router.push({path: '/login'})
      return
    }
  }
  config.headers.token = token
  return config
}, function (error) {
  return Promise.reject(error)
})

// 响应拦截
axios.interceptors.response.use(function (response) {
  // console.log(response)
  return response
}, function (error) {
  return Promise.reject(error.message)
})
